package Controller;

import DataAccess.DataAccessFacade;
import DomainModel.ClassWork;
import DomainModel.Role;
import DomainModel.Section;
import DomainModel.User;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mershack, Reynier
 */
@WebServlet(name = "ViewClassController", urlPatterns = {"/ViewClassController"})
public class ViewClassWorkController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        if (user == null || user.getRole() != Role.PROF) {
           request.getRequestDispatcher("/login").forward(request, response);
       }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        
        int sectionId = Integer.valueOf(request.getParameter("sid"));
        loadClassWorks(request, response, sectionId);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
          
        String actionBackToCourses = request.getParameter("backToCourses");
        String actionAddClassWork = request.getParameter("addClassWork");
        String actionDeleteClassWork = request.getParameter("submitDeleteClassWork");
        String actionEnterGrades = request.getParameter("enterGrades");
        
        if (actionBackToCourses != null) {
            response.sendRedirect("viewCourseSections");
        }
        else if (actionEnterGrades != null) {
            int sectionId = Integer.valueOf(request.getParameter("sectionId"));
            String strClassWorkId = request.getParameter("classWorkId");
            int classWorkId = (strClassWorkId == null || strClassWorkId.isEmpty()) ? 0 : Integer.parseInt(strClassWorkId);
            request.setAttribute("classWorkId", classWorkId);
            request.setAttribute("sectionId", sectionId);
            try {
                Section section = DataAccessFacade.getInstance().getSectionById(sectionId);
                List<User> students = DataAccessFacade.getInstance().getSectionStudents(sectionId);
                request.setAttribute("students", students);
                request.setAttribute("section",section);
              // request.getRequestDispatcher("/WEB-INF/grs/enterClassWorkGrades.jsp").forward(request, response);
                response.sendRedirect("enterClassWorkGrades?sid=" + sectionId + "&cwid=" + classWorkId);
                
            } catch (Exception ex) {
                Logger.getLogger(ViewClassWorkController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if (actionAddClassWork != null) {
            int sectionId = Integer.valueOf(request.getParameter("sectionId"));
            String classWorkId = request.getParameter("classWorkId");
            classWorkId = (classWorkId == null) ? "" : classWorkId;
            response.sendRedirect("enterClassWork?sid=" + sectionId + "&cwid=" + classWorkId);
        }
        else if (actionDeleteClassWork != null) {
            String strClassWorkId = request.getParameter("classWorkId");
            int classWorkId = (strClassWorkId == null || strClassWorkId.isEmpty()) ? 0 : Integer.parseInt(strClassWorkId);
            Map<String, String> messages = new HashMap<>();
            request.setAttribute("messages", messages);
                
            try { 
                HttpSession session = request.getSession();
                User user = (User) session.getAttribute("currentUser");
                boolean result = DataAccessFacade.getInstance().deleteClassWork(user.getUserId(), classWorkId);
                
                if (result) {
                    messages.put("success", "Class work deleted successfully");
                }
                else {
                    messages.put("error", "Could not delete the class work because grades have been given.");
                }
            }
            catch (Exception e) {
                messages.put("error", "An error occurred while deleting the class work");
            }
            finally {
                request.setAttribute("classWorkTypes", request.getParameter("classWorkTypes"));
                
                int sectionId = Integer.valueOf(request.getParameter("sectionId"));
                loadClassWorks(request, response, sectionId);
            }
        }
    }
    
    private void loadClassWorks(HttpServletRequest request, HttpServletResponse response, int sectionId)
            throws ServletException, IOException {
        processRequest(request, response);
        System.out.println(sectionId);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        try {
            DataAccessFacade dataAccessFacade = DataAccessFacade.getInstance();
            Section section;
            if(user.getRole()== Role.PROF){
                System.out.println("Here1");
                System.out.println("userid: "+ user.getUserId());
                section = dataAccessFacade.getSectionByIdAndProf(sectionId, user.getUserId());
                System.out.println(section.getProfessor().getFirstName());
            }
            else{
                System.out.println("Here2");
                section = dataAccessFacade.getSectionByIdAndUser(sectionId, user.getUserId());
            }
            
            List<ClassWork> classWorks = dataAccessFacade.getClassWorks(user.getUserId(), Integer.valueOf(sectionId));
            request.setAttribute("section", section);
            System.out.println(section.getProfessor().getFirstName());
            
            
            request.setAttribute("classWorks", classWorks);
            request.getRequestDispatcher("/WEB-INF/grs/viewClassWorks.jsp").forward(request, response);
        } catch (Exception e) {
        } finally {
        }
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
